import BluetoothModel, {DeviceState} from '../bluetooth/bluetoothmodel';
import BtController from '../bluetooth/btcontroller';
import BluetoothDevice from '../bluetooth/bluetoothdevice'

const TAG: string = 'BtConnector[Bluetooth]'

class Bluetooth {
    public btController: BtController = new BtController();
    public pairedDevices: BluetoothDevice[] = []
    autoUpdate: boolean = true
    callBack: (pDev: BluetoothDevice[], m: string, s: string, cS: string)=> void = null

    getConnectionState(): string {
        this.btController.refreshPairedDevices();
        this.pairedDevices = this.btController.get()
        let res = null
        this.pairedDevices.forEach(dev => {
            if(dev.connectionState === DeviceState.STATE_CONNECTED && dev.deviceType === 'HEADPHONE') {
                res = dev.deviceId
            }
        })
        return res
    }

    update():void{
        let conSt = this.getConnectionState()
        var message = null
        if (this.pairedDevices.length == 0) {
            message = 'There are currently no paired devices'
        }
        var state = "Status is：" + BluetoothModel.getStringState() +
        "\nThe current connection status is：" + BluetoothModel.getBtConnectionState()
        if (this.callBack != null) {
            this.callBack(this.pairedDevices, message, state, conSt)
        }
    }

    setEnable(on: boolean) {this.btController.setEnable(on)}

    isStateOn(): boolean {return this.btController.isStateOn()}

    connect(deviceId: string, con: boolean){
        if (con) {
            this.btController.connect(deviceId)
        } else {
            this.btController.disconnect(deviceId)
        }
    }

    setCallBack(callBack: (pDev: BluetoothDevice[], m: string, s: string, cS: string)=> void) {
        console.info(`${TAG} setCallBack ${callBack}`)
        this.callBack = callBack
    }
}

export let bluetooth = new Bluetooth()
